# -*- coding: utf-8 -*-
import requests
import json
# 导入函数库
from jqdata import *
from jqfactor import *
from jqboson.api.objects.order import UserOrder
from datetime import datetime as dt
from datetime import timedelta as td
"""
===========================免责声明=============================
本方案专为聚宽和QMT平台的模拟测试及策略研究等用途设计。客户若考
虑将其应用于实盘交易，需自行审慎评估并做出决策。对于所提供的网络
传输通道的稳定性，客户应自行进行判断。我方不提供任何关于策略盈亏
及通道稳定性的保证。
===========================免责声明=============================
【TraderLink聚宽跟单系统】使用说明
1、将本文件上传到聚宽的研究环境 https://www.joinquant.com/research
2、将以下代码粘贴到策略开头
================================================================
from TraderLinkApi import *
order = push_order(order)
order_target = push_order_target(order_target)
order_value = push_order_value(order_value)
order_target_value = push_order_target_value(order_target_value)
================================================================
3、代码添加完成，跑一次完整的回测，再添加到模拟运行，这样修改后的代码才会生效！
4、AUTH_CODE：联系作者获取，请务必保管好你的授权码，不要泄露
5、作者微信：traderlink 
"""

# 服务器地址
BASE_URL = 'http://trader.igateway.cn' 
# 授权码
AUTH_CODE = '联系作者获取'

def send_order(result): 
    # 获取当前时间戳
    current_time = dt.now().strftime("%Y-%m-%d %H:%M:%S")
    # 检查 result 是否是 UserOrder 类型
    if isinstance(result, UserOrder):
        url = '{}/api/open/v1/joinQuant/pushOrder'.format(BASE_URL)
        headers = {'Content-Type': 'application/json', 'auth-code': AUTH_CODE} 
        function_attributes = dir(result)
        data = {
            'status': str(result.status),
            'orderAddTime': str(result.add_time),
            'buySell': str(result.is_buy),
            'orderQuantity': str(result.amount),
            'filledQuantity': str(result.filled),
            'stockCode': str(result.security),
            'orderId': str(result.order_id),
            'averageTransactionPrice': str(result.price),
            'authCode': AUTH_CODE,
            'holdingCost': str(result.avg_cost),
            'longShort': str(result.side),
            'transactionFee': str(result.commission),
            'pushTime': current_time
        }
        print("【推送订单】  "+str(data))
        res = requests.post(url=url, data=json.dumps(data), headers=headers)   
        print(f"【推送结果】 "+res.text)
            
    else:
        pass
 
def push_order(func):
    """
    继承order对象 数据交易函数
    """

    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result == None:
            return
        send_order(result)
        return result

    return wrapper


def push_order_target(func):
    """
    继承order_target对象 百分比
    """

    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result == None:
            return
        send_order(result)
        return result

    return wrapper


def push_order_value(func):
    """
    继承order_value对象 数量
    """

    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs) 
        if result == None:
            return
        send_order(result)
        return result

    return wrapper


 
def push_order_target_value(func):
    """
    继承order_target_value对象 数量
    """ 
    def wrapper(*args, **kwargs):   
        result = func(*args, **kwargs) 
        if result == None:
            return
        send_order(result)
        return result

    return wrapper
